package com.example.springlearn.service.impl;

import com.example.springlearn.bean.AnsInfo;
import com.example.springlearn.mapper.AnsMapper;
import com.example.springlearn.service.AnsService;
import com.example.springlearn.util.StaticParamUtil;
import com.example.springlearn.util.redis.HashUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class AnsServiceImpl implements AnsService {

    @Resource
    AnsMapper ansMapper;

    @Resource
    HashUtil hashUtil;

    @Override
    public void updateGrade(AnsInfo ansInfo) {
        try {
            ansMapper.updateGrade(ansInfo);
        } catch (Exception e) {
            ansMapper.insertGrade(ansInfo);
        }
    }

    @Override
    public List<AnsInfo> queryGradesByUserId(Integer uid) {
        boolean b = hashUtil.hasHashKey(StaticParamUtil.ANSWER_INFO, uid.toString());
        if (!b) {
            List<AnsInfo> ansInfos = ansMapper.queryGradesByUserId(uid);
            hashUtil.hSet(StaticParamUtil.ANSWER_INFO, uid.toString(), ansInfos);
            log.info("用户答题数据从 mysql 中加载");
            return ansInfos;
        } else {
            log.info("用户答题数据从 redis 中加载");
            return (List<AnsInfo>) hashUtil.hGet(StaticParamUtil.ANSWER_INFO, uid.toString());
        }
    }
}
